﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System;
using System.Diagnostics;

namespace SL8.SL.Helpers
{
    /// <summary>
    /// Json帮助类
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="item">序列化的对象</param>
        /// <returns>Json格式的字符串</returns>
        public static string ToJson(this object item)
        {
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(item.GetType());
            ser.WriteObject(ms, item);
            byte[] json = ms.ToArray();
            ms.Close();

            return Encoding.UTF8.GetString(json, 0, json.Length);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">反序列化的目标类型</typeparam>
        /// <param name="jsonStr">用于反序列化的Json格式字符串</param>
        /// <returns>指定类型的对象</returns>
        public static T ToObject<T>(this string jsonStr)
        {
            try
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
                return (T)ser.ReadObject(ms);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ToObject 出错:{0}", ex);
                return default(T);
            }
        }
    }
}
